﻿using CBS.APP;
using CBS.DB.CBSEntity;
using CBS.Desktop.FormPage;
using CBS.Model.ManageModel;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CBS.Desktop.ViewPartial
{
    /// <summary>
    /// StudentSignDetail.xaml 的交互逻辑
    /// </summary>
    public partial class StudentSignDetail : UserControl
    {
        public Pagination pager = new Pagination() { rows = 10, page = 1, sidx = nameof(StudentSignInViewModel.SighInId), sord = "desc" };

        private bool _isSemesterDataBound = false;
        private bool _isGradeDataBound = false;
        private bool _isClassDataBound = false;
        private bool _isCourseDataBound = false;

        public StudentSignDetail()
        {
            InitializeComponent();

            LoadCondation();
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                // 调用处理方法
                pager.page = 1;
                pg_DataList.PageIndex = 1;
                FlushGrid();
                e.Handled = true; // 如果需要，标记事件已处理
            }
        }

        private async void LoadCondation()
        {
            btn_Delete.IsEnabled = false;
            btn_Import.IsEnabled = false;
            btn_Search.IsEnabled = false;
            btn_Selected.IsEnabled = false;

            // 加载 ComboBox 数据
            await LoadDataAsync();

            BindLesson();

            // 查询 Grid 数据
            //FlushGrid();

            btn_Search.IsEnabled = true;
            btn_Delete.IsEnabled = true;
            btn_Import.IsEnabled = true;
            btn_Selected.IsEnabled = true;
        }

        private async Task LoadDataAsync()
        {
            // 使用 Task.WhenAll 等待所有 ComboBox 数据加载完成
            var tasks = new List<Task>
            {
                BindSemester(),
                BindGrade(),
                BindClass(),
                BindCourse(),
            };

            await Task.WhenAll(tasks);
        }

        private async Task BindSemester()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => SemesterApp.GetSelectList());

                if (list.Count == 0)
                {
                    return;
                }


                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;
                }));
                cb_Semester.SelectedIndex = 0;

                // 设置标志为 true
                _isSemesterDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async Task BindGrade()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => GradeApp.GetSelectList());

                list.Insert(0, new GradeViewModel { GradeId = 0, GradeName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Grade.ItemsSource = list;
                }));
                cb_Grade.SelectedIndex = 0;

                // 设置标志为 true
                _isGradeDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindClass()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => ClassApp.GetSelectList());

                list.Insert(0, new ClassViewModel { ClassId = 0, ClassName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Class.ItemsSource = list;
                }));
                cb_Class.SelectedIndex = 0;

                // 设置标志为 true
                _isClassDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindCourse()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => CourseApp.GetSelectList());

                list.Insert(0, new CourseViewModel { CourseId = 0, CourseName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Course.ItemsSource = list;
                }));
                cb_Course.SelectedIndex = 0;

                // 设置标志为 true
                _isCourseDataBound = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void BindLesson()
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;

                var list = await Task.Run(() => LessonApp.GetSelectList(semesterId, gradeId, classId, courseId));

                list.Insert(0, new LessonSelectModel { LessonId = 0, LessonTime = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Lesson.ItemsSource = list;
                }));
                cb_Lesson.SelectedIndex = 0;


                FlushGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async void FlushGrid()
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                int lessonId = ((LessonSelectModel)cb_Lesson.SelectedItem).LessonId;
                string studentInfo = tb_Student.Text.Trim();

                var data = await Task.Run(() => StudentSignInApp.GetList(pager, semesterId, gradeId, classId, courseId, lessonId, studentInfo));

                this.Dispatcher.Invoke(() =>
                {
                    pg_DataList.MaxPageCount = pager.total;
                    dgr_DataList.ItemsSource = data;
                    btn_Search.IsEnabled = true;
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void dg_Delete(object sender, RoutedEventArgs e)
        {
            try
            {
                var tmp = sender as System.Windows.Controls.Button;
                var data = tmp.DataContext as StudentSignInInfoViewModel;
                if (StudentSignInApp.DeleteStudentSignIn(data.SighInId))
                {
                    FlushGrid();
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void btn_Import_Click(object sender, RoutedEventArgs e)
        {
            ImportStudentSignDetailFormCondition formCondition = new()
            {
                SemesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId,
                GradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId,
                ClassId = ((ClassViewModel)cb_Class.SelectedItem).ClassId,
                CourseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId,
                LessonId = ((LessonSelectModel)cb_Lesson.SelectedItem).LessonId,
            };
            ImportStudentSignDetail signDetail = new(formCondition)
            {
                Owner = Window.GetWindow(this)
            };
            var dialogResult = signDetail.ShowDialog();
            if (dialogResult.HasValue && dialogResult.Value)
            {
                FlushGrid();
            }
        }

        private void btn_Selected_Click(object sender, RoutedEventArgs e)
        {
            ImportStudentSignDetailFormCondition formCondition = new()
            {
                SemesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId,
                GradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId,
                ClassId = ((ClassViewModel)cb_Class.SelectedItem).ClassId,
                CourseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId,
                LessonId = ((LessonSelectModel)cb_Lesson.SelectedItem).LessonId,
            };
            CheckStudentSignDetail signDetail = new(formCondition)
            {
                Owner = Window.GetWindow(this)
            };
            var dialogResult = signDetail.ShowDialog();
            if (dialogResult.HasValue && dialogResult.Value)
            {
                FlushGrid();
            }
        }

        private void btn_Delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                string semesterName = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterName;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                string gradeName = ((GradeViewModel)cb_Grade.SelectedItem).GradeName;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                string className = ((ClassViewModel)cb_Class.SelectedItem).ClassName;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;
                string courseName = ((CourseViewModel)cb_Course.SelectedItem).CourseName;
                int lessonId = ((LessonSelectModel)cb_Lesson.SelectedItem).LessonId;
                string lessonName = ((LessonSelectModel)cb_Lesson.SelectedItem).LessonTime;
                string studentInfo = tb_Student.Text.Trim();

                string confirmMessage = $"即将批量删除{semesterName}-{(gradeId == 0 ? "所有年级" : gradeName)}-{(classId == 0 ? "所有班级" : className)}-{(courseId == 0 ? "所有课程" : courseName)}-{(lessonId == 0 ? "所有课程" : lessonName)}的签到记录。确认删除吗？";

                var result = MessageBox.Show(Window.GetWindow(this), confirmMessage, "批量删除警告", MessageBoxButton.OKCancel, MessageBoxImage.Warning);
                if (MessageBoxResult.OK == result)
                {
                    if (StudentSignInApp.BatchDeleteStudentSignIn(semesterId, gradeId, classId, courseId, lessonId, studentInfo))
                    {
                        FlushGrid();
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void btn_Search_Click(object sender, RoutedEventArgs e)
        {
            pager.page = 1;
            pg_DataList.PageIndex = 1;
            FlushGrid();
        }

        private void cb_Semester_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isSemesterDataBound)
                return;
            BindLesson();
        }

        private void cb_Grade_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isGradeDataBound)
                return;
            BindLesson();
        }
        private void cb_Class_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isClassDataBound)
                return;
            BindLesson();
        }
        private void cb_Course_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!_isCourseDataBound)
                return;
            BindLesson();
        }

        private void pg_DataList_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            pager.page = e.Info;
            FlushGrid();
        }

        private void dgr_DataList_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            // 设置行头为行号（从1开始）
            e.Row.Header = (e.Row.GetIndex() + 1).ToString();
        }
    }
}
